from frame_work.setting import *
from frame_work.yaml_file import YAML
from frame_work .util import check_tid, assert_equal, get_sql_info
from frame_work.logger import Logger
from frame_work.login import AdminLogin, SystemLogin
from frame_work import menu_list
logger = Logger(logger="activity").get_logger()


class Activity(object):

    def __init__(self, tid):
        self.tid = tid
        self.info = self.get_activity_info()
        self.yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))
        self.logger = Logger(logger="Activity").get_logger()

    def get_activity_info(self):
        """
        查询操作活动的信息
        :return:
        """
        statement = """SELECT
                        days,
                        guaranty,
                        state,
                        LEVEL
                    FROM
                        sk_try
                    WHERE
                        tid = %s"""
        params = (self.tid,)
        value = get_sql_info(statement, params, meta={
            "info": "查询操作活动的信息"
        })
        return value[0]


class AdminActivity(Activity):

    def __init__(self, tid):
        super().__init__(tid)
        self.session = self.get_session()

    def get_session(self):
        """
        获取登录session
        :return:
        """
        login = AdminLogin()
        login.admin_card_login()
        return login.get_session()

    def audit_pass_activity(self):
        """
        管理员审核通过活动
        :return:
        """
        days = self.info.get("days")
        yaml_data = self.yaml.get_data('audit_activity')
        url = yaml_data.get('url') + '?tid=' + \
            str(self.tid) + '&days=' + str(days)
        logger.debug("开始执行审核通过活动操作...")
        response = self.session.get(url, headers=yaml_data.get('header')).text
        res_cn = response.encode('utf-8').decode('unicode_escape')
        # 接口响应内容是这种的：<meta
        # charset="utf-8"><script>alert("\u5ba1\u6838\u6210\u529f!");</script><script>window.location.href=document.referrer;</script>
        assert_equal('审核成功', res_cn, '管理员审核活动')

    def online_activity(self):
        """
        管理员上线活动
        :return:
        """
        guaranty = self.info.get("guaranty")
        if guaranty:
            yaml_data = self.yaml.get_data('online_activity')
            url = yaml_data.get('url') + '?tid=' + str(self.tid)
            logger.debug("开始执行上线活动操作...")
            response = self.session.get(
                url, headers=yaml_data.get('header')).text
            res_cn = response.encode('utf-8').decode('unicode_escape')
            assert_equal('上线成功', res_cn, '管理员上线活动')
        else:
            logger.debug("该活动没有支付担保金...")

    def shield_acticity(self):
        """
        管理员屏蔽活动
        :return:
        """
        yaml_data = self.yaml.get_data('shield_acticity')
        yaml_data.get('data').update({'tid': self.tid})
        logger.debug("开始执行屏蔽活动操作...")
        response = self.session.post(
            url=yaml_data.get('url'),
            data=yaml_data.get('data'),
            headers=yaml_data.get('header')).text
        assert_equal('屏蔽成功', response, '管理员屏蔽活动')

    def remove_shield_acticity(self):
        """
        管理员解除屏蔽活动
        :return:
        """
        yaml_data = self.yaml.get_data('remove_shield_acticity')
        url = yaml_data.get('url') + '?tid=' + str(self.tid)
        logger.debug("开始执行解除屏蔽活动操作...")
        response = self.session.get(url, headers=yaml_data.get('header')).text
        assert_equal('解除成功', response, '管理员解除屏蔽活动')

    # def settle_activity(self):
    #     """
    #     管理员结算活动
    #     :return:
    #     """
    #     settle_activity = global_config.get_url("settle_activity")
    #     state = self.info.get("state")
    #     level = self.info.get("level")
    #     if state == 4:
    #         if level != 1:
    #             post_data = self.public.post_data(29,tid=self.tid)
    #         else:
    #             post_data = self.public.post_data(30,tid=self.tid)
    #         logger.debug("开始执行结算活动操作...")
    #         response = self.session.post(settle_activity,data = post_data,headers = self.header).text
    #         assert_equal('结算成功',response,'管理员结算活动')
    #     else:
    #         logger.debug("该活动状态不是已结束，无法结算！")


class ActivitySys(Activity):
    """
    system站点执行结束活动操作
    """

    def __init__(self, tid):
        super().__init__(tid)
        self.session = self.get_session()

    def get_session(self):
        """
        system用户登录
        :return:
        """
        login = SystemLogin()
        login.sksystem_login()
        return login.get_session()

    def offline_acticity(self):
        """
        system管理员下线活动
        :return:
        """
        state = self.info.get("state")
        if state == 3:
            yaml_data = self.yaml.get_data('system_offline_activity')
            url = yaml_data.get('url') + '/' + str(self.tid)
            self.logger.debug("开始执行下线活动操作...")
            response = self.session.get(url).text
            assert_equal('true', response, '管理员下线活动')
        else:
            self.logger.debug("该活动状态不是进行中状态，无法执行下线操作...")


def main():
    while True:
        # 选择功能菜单
        menu_list.activity_menu()
        # 选择
        choise = input("请输入您的选择: ")
        if choise in ('q', 'Q'):
            break
        try:
            tid = int(input(u'请输入活动tid: '))
            status = check_tid(tid)
            if not status:
                raise Exception("活动tid不存在try表，请核实后在重新输入")
        except Exception as e:
            logger.error("reszon => %s" % e)
        else:
            if choise == '1':
                admin_act = AdminActivity(tid)
                admin_act.audit_pass_activity()
            elif choise == '2':
                admin_act = AdminActivity(tid)
                admin_act.online_activity()
            elif choise == '3':
                admin_act = AdminActivity(tid)
                admin_act.shield_acticity()
            elif choise == '4':
                admin_act = AdminActivity(tid)
                admin_act.remove_shield_acticity()
            elif choise == '5':
                system_act = ActivitySys(tid)
                system_act.offline_acticity()
            else:
                logger.info("没有对应的选项,请按选项输入...")
                break


if __name__ == "__main__":
    main()
